package com.alibaba.boot.netty.netty.http;

import com.sun.jndi.toolkit.url.Uri;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //读取客户端数据

        if (msg instanceof HttpRequest){

            System.out.println("msg type="+msg.getClass());
            System.out.println("client address:"+ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest) msg;

            Uri uri = new Uri(httpRequest.uri());

            if (uri.getPath().contains("icon")){
                System.out.println("过滤资源");
                return;
            }

            //回复信息
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello this is server", CharsetUtil.UTF_8);
            DefaultHttpResponse defaultHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
            defaultHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            defaultHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

            ctx.writeAndFlush(defaultHttpResponse);
        }
    }
}
